package com.hz.userService.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hz.userService.domain.Class;
import com.hz.userService.domain.Grade;
import com.hz.userService.service.ClassService;
import com.hz.userService.mapper.ClassMapper;
import com.hz.userService.service.GradeService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
* @author li
* @description 针对表【classes(班级表)】的数据库操作Service实现
* @createDate 2023-09-23 17:10:28
*/
@Service
public class ClassServiceImpl extends ServiceImpl<ClassMapper, Class>
    implements ClassService{

    @Resource
    ClassMapper classMapper;

    @Resource
    GradeService gradeService;

    @Override
    public Boolean addClass(String className, Integer gradeId) {
        Class clas = new Class();

        /* 判断班级名称是否重复 */
        Map<String,Object> map = new HashMap<>();
        map.put("class_name",className);
        if (classMapper.selectByMap(map).size() != 0)
            return false;

        /* 添加班级数据 */
        clas.setClassName(className);
        clas.setGradeId(gradeId);

        /* 获取年级数据 */
        Grade grade = gradeService.viewGrade(clas.getGradeId());

        /* 添加年级数据 */
        clas.setGradeName(grade.getGradeName());
        clas.setGradeYear(grade.getGradeYear());


        /* 添加成功返回true */
        return classMapper.insert(clas)!=0;
    }

    @Override
    public Boolean editClass(Integer id, String className, Integer gradeId) {
        Class clas = classMapper.selectById(id);

        /* 若class不存在返回false */
        if (clas == null)
            return false;

        /* 修改班级数据 */
        clas.setClassName(className);
        clas.setGradeId(gradeId);

        /* 获取年级数据 */
        Grade grade = gradeService.viewGrade(clas.getGradeId());

        /* 修改年级数据 */
        clas.setGradeName(grade.getGradeName());
        clas.setGradeYear(grade.getGradeYear());

        /* 修改成功返回true */
        return classMapper.updateById(clas)!=0;
    }

    @Override
    @CacheEvict(value = "class_",key = "#id")
    public Boolean deleteClass(Integer id) {
        /* 删除成功返回true */
        return classMapper.deleteById(id)!=0 ;
    }

    @Override
    @Cacheable(value = "class_",key = "#id")
    public Class viewClass(Integer id) {
        return classMapper.selectById(id);
    }
}




